package com.xcx.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xcx.constant.JwtClaimsConstant;
import com.xcx.context.BaseContext;
import com.xcx.entity.UserIdentity;
import com.xcx.properties.JwtProperties;
import com.xcx.result.Result;
import com.xcx.utils.JwtUtil;
import com.xcx.utils.SQLUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/xcx/user")
@Slf4j
public class UserController {
    private RestTemplate restTemplate;

    @Autowired
    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     *
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> map) {

        String url = "https://qyapi.weixin.qq.com/cgi-bin/miniprogram/jscode2session?access_token=" + getToken() + "&js_code=" + map.get("code") + "&grant_type=authorization_code";
        String object = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject2 = JSON.parseObject(object);
        log.info("{}", jsonObject2);
        if (jsonObject2.getInteger("errcode") != 0) {
            return Result.error("登录失败，未获取到工号!");
        }
        String userid = jsonObject2.getString("userid");
        JSONObject jsonObject = new JSONObject();
        if (Integer.parseInt(map.get("isFirst")) == 1) {
            short storeLevel = 0;
            short companyLevel = 0;
            short isHead = 0;
            String sql1 = "select c.code,c.name,c.depart,c.dingzw,c.bigarea,c.mediumarea,c.ds,c.smallarea,c.zw,d.orgtype,d.name departname from (select b.code code,b.name name,b.departcode depart,b.dingzw dingzw,a.bigarea,a.mediumarea,a.ds,a.smallarea,a.zw zw from rm_da_qw_employees b  left JOIN manager_data_table a ON a.code = b.code where b.code = '" + userid + "') c left join rm_da_qw_departs d on c.depart = d.code";
            List<UserIdentity> userIdentities = jdbcTemplate.query(sql1, new RowMapper<UserIdentity>() {
                @Override
                public UserIdentity mapRow(ResultSet rs, int rowNum) throws SQLException {
                    UserIdentity user = new UserIdentity();
                    user.setCode(rs.getString("code"));
                    user.setName(rs.getString("name"));
                    user.setDepart(rs.getString("depart"));
                    user.setDingzw(rs.getString("dingzw"));
                    user.setZw(rs.getShort("zw"));
                    user.setBigarea(rs.getString("bigarea"));
                    user.setMediumarea(rs.getString("mediumarea"));
                    user.setSmallarea(rs.getString("smallarea"));
                    user.setOrgtype(rs.getString("orgtype"));
                    user.setDepartname(rs.getString("departname"));
                    return user;
                }
            });
            String[] departName = new String[userIdentities.size()];
            String[] departCode = new String[userIdentities.size()];
            if (userIdentities.size() == 0) {
                return Result.error("工号无效");
            } else {
                UserIdentity userIdentity = userIdentities.get(0);
                short zw = userIdentity.getZw();
                String orgtype = userIdentity.getOrgtype();
                String dingzw = userIdentity.getDingzw();
                if (zw != 0) {
                    //经理
                    storeLevel = zw;
                    if (zw == 5) {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getSmallarea();
                            departCode[i] = userIdentity1.getDepart();
                        }
                    }else if (zw == 6) {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getDs();
                            departCode[i] = userIdentity1.getDepart();
                        }
                    } else if (zw == 7) {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getMediumarea();
                            departCode[i] = userIdentity1.getDepart();
                        }
                    } else if (zw == 9) {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getBigarea();
                            departCode[i] = userIdentity1.getDepart();
                        }
                    }
                } else {
                    //非经理
                    //总部
                    if (("公司".equals(orgtype) || "部门".equals(orgtype))) {
                        //总部人员
                        isHead = 1;
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getDepartname();
                            departCode[i] = userIdentity1.getDepart();
                        }
                        if ("副部长".equals(dingzw) || "部长".equals(dingzw) || "总监助理".equals(dingzw)) {
                            companyLevel = 5;
                        } else {
                            companyLevel = 3;
                        }
                    } else {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getDepartname();
                            departCode[i] = userIdentity1.getDepart();
                        }
                        //非经理
                        if ("门店".equals(orgtype) && dingzw.startsWith("店长")) {
                            //店长
                            storeLevel = 2;
                        } else {
                            //店员
                            storeLevel = 1;
                        }
                    }
                }
//                if (("公司".equals(orgtype) || "部门".equals(orgtype))) {
//                    //总部人员
//                    isHead = 1;
//                    for (int i = 0; i < userIdentities.size(); i++) {
//                        UserIdentity userIdentity1 = userIdentities.get(i);
//                        departName[i] = userIdentity1.getDepartname();
//                        departCode[i] = userIdentity1.getDepart();
//                    }
//                    if ("副部长".equals(dingzw) || "部长".equals(dingzw) || "总监助理".equals(dingzw)) {
//                        companyLevel = 5;
//                    } else {
//                        companyLevel = 3;
//                    }
//                } else {
//                    //非总部
//                    isHead = 0;
//                    for (int i = 0; i < userIdentities.size(); i++) {
//                        UserIdentity userIdentity1 = userIdentities.get(i);
//                        departName[i] = userIdentity1.getDepartname();
//                        departCode[i] = userIdentity1.getDepart();
//                    }
//                    if (zw == 0) {
//                        //非经理
//                        if ("门店".equals(orgtype) && dingzw.startsWith("店长")) {
//                            //店长
//                            storeLevel = 2;
//                        } else {
//                            //店员
//                            storeLevel = 1;
//                        }
//                    } else {
//                        //经理
//                        storeLevel = zw;
//                        if (zw == 5) {
//                            for (int i = 0; i < userIdentities.size(); i++) {
//                                UserIdentity userIdentity1 = userIdentities.get(i);
//                                departName[i] = userIdentity1.getSmallarea();
//                                departCode[i] = userIdentity1.getDepart();
//                            }
//                        } else if (zw == 7) {
//                            for (int i = 0; i < userIdentities.size(); i++) {
//                                UserIdentity userIdentity1 = userIdentities.get(i);
//                                departName[i] = userIdentity1.getMediumarea();
//                                departCode[i] = userIdentity1.getDepart();
//                            }
//                        } else if (zw == 9) {
//                            for (int i = 0; i < userIdentities.size(); i++) {
//                                UserIdentity userIdentity1 = userIdentities.get(i);
//                                departName[i] = userIdentity1.getBigarea();
//                                departCode[i] = userIdentity1.getDepart();
//                            }
//                        } else {
//
//                        }
//                    }
//                }
            }
            jsonObject.put("isHead", isHead);
            jsonObject.put("departName", departName);
            jsonObject.put("departCode", departCode);
            jsonObject.put("storeLevel", storeLevel);
            jsonObject.put("companyLevel", companyLevel);
        }

        //校验工号
        String sql = "select * from rm_da_qw_employees where state = 0 and code = '" + userid + "'";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        if (maps.size() == 0) return Result.error("工号无效");

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, userid);
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        jsonObject.put("userId", userid);
        jsonObject.put("token", token);
        log.info("登录相关信息{}", jsonObject);
        return Result.success(jsonObject);
    }

    @PostMapping("/login2")
    public Result login2(@RequestBody Map<String, String> map) {
        String userid = map.get("userId");
        String sql6 = "select password from xcx_change_password where userId = ?";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql6, userid);
        if (mapList.size() == 0){
            if (!"123456".equals(map.get("password"))) {
                return Result.error("密码错误");
            }
        }else {
            String password = mapList.get(0).get("password").toString();
            String password1 = map.get("password");
            String md5Hex = DigestUtils.md5Hex(password1);
            if (!md5Hex.equals(password)){
                return Result.error("密码错误");
            }
        }


        JSONObject jsonObject = new JSONObject();
        if (Integer.parseInt(map.get("isFirst")) == 1) {
            short storeLevel = 0;
            short companyLevel = 0;
            short isHead = 0;
            String sql1 = "select c.code,c.name,c.depart,c.dingzw,c.bigarea,c.mediumarea,c.ds,c.smallarea,c.zw,d.orgtype,d.name departname from (select b.code code,b.name name,b.departcode depart,b.dingzw dingzw,a.bigarea,a.mediumarea,a.ds,a.smallarea,a.zw zw from rm_da_qw_employees b  left JOIN manager_data_table a ON a.code = b.code where b.code = '" + userid + "') c left join rm_da_qw_departs d on c.depart = d.code";
            List<UserIdentity> userIdentities = jdbcTemplate.query(sql1, new RowMapper<UserIdentity>() {
                @Override
                public UserIdentity mapRow(ResultSet rs, int rowNum) throws SQLException {
                    UserIdentity user = new UserIdentity();
                    user.setCode(rs.getString("code"));
                    user.setName(rs.getString("name"));
                    user.setDepart(rs.getString("depart"));
                    user.setDingzw(rs.getString("dingzw"));
                    user.setZw(rs.getShort("zw"));
                    user.setBigarea(rs.getString("bigarea"));
                    user.setMediumarea(rs.getString("mediumarea"));
                    user.setDs(rs.getString("ds"));
                    user.setSmallarea(rs.getString("smallarea"));
                    user.setOrgtype(rs.getString("orgtype"));
                    user.setDepartname(rs.getString("departname"));
                    return user;
                }
            });
            String[] departName = new String[userIdentities.size()];
            String[] departCode = new String[userIdentities.size()];
            if (userIdentities.size() == 0) {
                return Result.error("工号无效");
            } else {
                UserIdentity userIdentity = userIdentities.get(0);
                short zw = userIdentity.getZw();
                String orgtype = userIdentity.getOrgtype();
                String dingzw = userIdentity.getDingzw();
                if (zw != 0) {
                    //经理
                    storeLevel = zw;
                    if (zw == 5) {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getSmallarea();
                            departCode[i] = userIdentity1.getDepart();
                        }
                    }else if (zw == 6) {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getDs();
                            departCode[i] = userIdentity1.getDepart();
                        }
                    } else if (zw == 7) {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getMediumarea();
                            departCode[i] = userIdentity1.getDepart();
                        }
                    } else if (zw == 9) {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getBigarea();
                            departCode[i] = userIdentity1.getDepart();
                        }
                    }
                } else {
                    //非经理
                    //总部
                    if (("公司".equals(orgtype) || "部门".equals(orgtype))) {
                        //总部人员
                        isHead = 1;
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getDepartname();
                            departCode[i] = userIdentity1.getDepart();
                        }
                        if ("副部长".equals(dingzw) || "部长".equals(dingzw) || "总监助理".equals(dingzw)) {
                            companyLevel = 5;
                        } else {
                            companyLevel = 3;
                        }
                    } else {
                        for (int i = 0; i < userIdentities.size(); i++) {
                            UserIdentity userIdentity1 = userIdentities.get(i);
                            departName[i] = userIdentity1.getDepartname();
                            departCode[i] = userIdentity1.getDepart();
                        }
                        //非经理
                        if ("门店".equals(orgtype)&& dingzw!=null && dingzw.startsWith("店长")) {
                            //店长
                            storeLevel = 2;
                        } else {
                            //店员
                            storeLevel = 1;
                        }
                    }
                }
            }
            jsonObject.put("isHead", isHead);
            jsonObject.put("departName", departName);
            jsonObject.put("departCode", departCode);
            jsonObject.put("storeLevel", storeLevel);
            jsonObject.put("companyLevel", companyLevel);
        }

        //校验工号
        String sql = "select * from rm_da_qw_employees where state = 0 and code = '" + userid + "'";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        if (maps.size() == 0) return Result.error("工号无效");

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, userid);
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        jsonObject.put("userId", userid);
        jsonObject.put("token", token);
        log.info("登录相关信息{}", jsonObject);
        return Result.success(jsonObject);
    }

    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody Map<String, String> map) throws UnsupportedEncodingException {
        String userId = map.get("userId");
        String oldPassword = map.get("oldPassword");
        String newPassword = map.get("newPassword");

        if (userId != null && oldPassword != null && newPassword != null){
            String sql1 = "select password from xcx_change_password where userId = ?";
            List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql1, userId);
            if (mapList.size() == 1){
                String md5New = DigestUtils.md5Hex(newPassword.getBytes("UTF-8"));
                String md5Old = DigestUtils.md5Hex(oldPassword.getBytes("UTF-8"));
                if (md5Old.equals(mapList.get(0).get("password"))){
                    String sql2 = "UPDATE xcx_change_password SET password = ?, updatedate = NOW() WHERE userId = ?";
                    int update = jdbcTemplate.update(sql2, md5New, userId);
                    return update==1?Result.success():Result.error("修改失败");
                }else {
                    return Result.error("旧密码错误,如果忘记，联系数据中心");
                }
            }else {
                String md5New = DigestUtils.md5Hex(newPassword.getBytes("UTF-8"));
                String sql3 = "INSERT INTO xcx_change_password (userId, password,updatedate) VALUES (?, ?,now())";
                int update = jdbcTemplate.update(sql3, userId, md5New);
                return update==1?Result.success():Result.error("修改失败");
            }
        }else {
            return Result.error("数据异常");
        }
    }

    @GetMapping("/auth")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response){
        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());

        //2、校验令牌
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            String empId = claims.get(JwtClaimsConstant.EMP_ID).toString();
            log.info("员工校验通过：{}", empId);
            response.setStatus(200);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401 状态码
            response.setStatus(401);
            return false;
        }
    }

    public String getToken() {
        redisTemplate.delete("access_token");
        String access_token = (String) redisTemplate.opsForValue().get("access_token");
        if (access_token == null) {
            String path = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwed5e7f3fd1a3a553&corpsecret=D6D5neGQj7ifmrlbsu3EzBYrw7MJ274OUPVsfIZxDDc";
            String forObject = restTemplate.getForObject(path, String.class);
            JSONObject json = JSONObject.parseObject(forObject);
            access_token = json.getString("access_token");
            redisTemplate.opsForValue().set("access_token", access_token, 100, TimeUnit.MINUTES);
            return access_token;
        } else {
            return access_token;
        }
    }


}
